package main

import (
	"encoding/json"
	"fmt"
)

// JSON 反序列化
// func Unmarshal(data []byte, v interface{}) error

type Student struct {
	Name     string
	Age      byte
	Birthday string
}

func testStruct() {
	stu := Student{"jack", 12, "2020-2-11"}
	data, _ := json.Marshal(stu)
	fmt.Println(string(data))

	var s1 Student
	if err := json.Unmarshal(data, &s1); err != nil {
		fmt.Println("struct Unmarshal err is ", err)
	}
	fmt.Println(s1)
	// {"Name":"jack","Age":12,"Birthday":"2020-2-11"}
	// {jack 12 2020-2-11}
}

func testMap() {
	m := make(map[string]interface{})
	m["a"] = "aa"
	m["b"] = "bb"
	m["arr"] = []string{"aa", "bb", "cc"}

	data, _ := json.Marshal(m)
	fmt.Println(string(data))

	var m1 map[string]interface{}
	if err := json.Unmarshal(data, &m1); err != nil {
		fmt.Println("struct Unmarshal err is ", err)
	}
	fmt.Println(m1)
	// {"a":"aa","arr":["aa","bb","cc"],"b":"bb"}
	// map[a:aa arr:[aa bb cc] b:bb]
}

func testSlice() {
	var slice []map[string]interface{}

	m := make(map[string]interface{})
	m["a"] = "aa"
	m["b"] = "bb"
	slice = append(slice, m)

	m1 := make(map[string]interface{})
	m1["d"] = "dd"

	slice = append(slice, m1)

	data, err := json.Marshal(slice)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(data)) // [{"a":"aa","b":"bb"},{"d":"dd"}]

	var sli1 []map[string]interface{}
	if e := json.Unmarshal(data, &sli1); e != nil {
		fmt.Println(e)
	}
	fmt.Println(sli1) // [map[a:aa b:bb] map[d:dd]]

}

func main() {
	testStruct()
	fmt.Println("----------------------")
	testMap()
	fmt.Println("----------------------")
	testSlice()
}
